package com.kevin.learn.thread;

/**
 * 使用两个线程打印 1-100。线程1, 线程2 交替打印
 */
public class NumberTest {
    public static void main(String[] args) {
        Number number = new Number();
        Thread t1 = new Thread(number);
        Thread t2 = new Thread(number);
        t1.start();
        t2.start();
    }
}

class Number implements Runnable {
    private int num = 0;
    private Object obj = new Object();

    @Override
    public void run() {
        while (true) {
            synchronized (this) {
                notify();
//                this.notify();
//            synchronized (obj) {
                //    this.notify();  error
//                obj.notify();
                if (num <= 100) {
                    System.out.println(Thread.currentThread().getName() + ":" + num);
                    num++;
                } else {
                    break;
                }
                try {
                    wait();//this.wait();
//                    obj.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
